package com.example.opengldemo.simple_13_02;

import android.opengl.Matrix;

import com.example.opengldemo.util.MatrixState;

import static com.example.opengldemo.simple_13_02.Constant.XBOUNDARY;
import static com.example.opengldemo.simple_13_02.Constant.ZBOUNDARY;


public class BallForControl {
	MySurfaceView mv;
	Ball ball;
	
	float rotateX;
	float rotateY;
	float rotateZ;
	
	float tempX;
	float tempZ;
	
	float tempSPANX;
	float tempSPANZ;
	
	float tempLength;
	
	float tempAngle;

	float[] selfRotateMatrix;
	
	public BallForControl(MySurfaceView mv,float scale,float aHalf,int n)
	{
		this.mv=mv;
		ball=new Ball(mv,scale,aHalf,n);
		selfRotateMatrix=new float[16];
		Matrix.setRotateM(selfRotateMatrix, 0, 10, 0, 1, 0);
	}
	
	public void drawSelf()
	{
		MatrixState.pushMatrix();
		MatrixState.translate(Constant.XOFFSET, 1.2f, Constant.ZOFFSET);
		MatrixState.matrix(selfRotateMatrix);
		ball.drawSelf();		
		MatrixState.popMatrix();
	}
	

	public void go(){
		tempSPANX=Constant.SPANX;
		tempSPANZ=Constant.SPANZ;
		
		tempX=Constant.XOFFSET+tempSPANX;
		tempZ=Constant.ZOFFSET+tempSPANZ;
		
		

		if( (tempZ<-ZBOUNDARY)||(tempZ>ZBOUNDARY))
		{	
			tempSPANZ=0;
		}
		if((tempX<-XBOUNDARY)|| (tempX>XBOUNDARY))
		{
			tempSPANX=0;
		}
		Constant.XOFFSET+=tempSPANX;
		Constant.ZOFFSET+=tempSPANZ;
		rotateX=tempSPANZ;
		rotateY=0;
		rotateZ=-tempSPANX;
		tempLength=(float) Math.sqrt(tempSPANX*tempSPANX+tempSPANZ*tempSPANZ);
		tempAngle=(float) Math.toDegrees(tempLength/Constant.BALLR);
		if(Math.abs(tempAngle)!=0&&(Math.abs(rotateZ)!=0||Math.abs(rotateX)!=0))
		{
			float[] newMatrix=new float[16];
			Matrix.setRotateM(newMatrix, 0, tempAngle, rotateX, rotateY, rotateZ);
			float[] resultMatrix=new float[16];
			Matrix.multiplyMM(resultMatrix, 0, newMatrix, 0, selfRotateMatrix,0);
			selfRotateMatrix=resultMatrix;
		}
	}	
}
